import requests
import json


class BaiduTranslator:

    def __init__(self):
        self.headers = {"User-Agent":"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Mobile Safari/537.36"}

    def langdetect(self, words):
        url = 'http://fanyi.baidu.com/langdetect'
        data = {
            'query': words
        }
        response = requests.post(url, data=data)
        lang_info = json.loads(response.content.decode())
        return lang_info['lan']

    def translator(self, words):
        url = 'http://fanyi.baidu.com/basetrans'
        data = {
            'query': words,
            'from': self.langdetect(words)
        }
        data['to'] = 'zh' if data['from'] == 'en' else 'en'
        response = requests.post(url, data=data, headers=self.headers)
        lang_info = response.json()
        return lang_info['trans'][0]['dst']


class YoudaoTranslator:

    def __init__(self):
        self.headers = {"User-Agent":"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Mobile Safari/537.36"}

    def translator(self, words):
        url = 'http://m.youdao.com/translate'
        data = {
            'inputtext': words,
            'type': 'AUTO'
        }
        response = requests.post(url, data=data, headers=self.headers)
        html_str = response.content.decode()
        ul_start = '<ul id="translateResult">'
        li_start = '<li>'
        li_end = '</li>'
        ul_start_pos = html_str.find(ul_start) + len(ul_start)
        li_start_pos = html_str.find(li_start, ul_start_pos) + len(li_start)
        li_end_pos = html_str.find(li_end, ul_start_pos)
        print(html_str[li_start_pos:li_end_pos])


class CibaTranslator:

    def __init__(self):
        self.headers = {"User-Agent":"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Mobile Safari/537.36"}

    def translator(self, words):
        url = 'http://fy.iciba.com/ajax.php?a=fy'
        data = {
            'f': 'auto',
            't': 'auto',
            'w': words
        }
        response = requests.post(url, data=data, headers=self.headers)
        info = response.json()
        print(info['content']['out'])


if __name__ == '__main__':
    youdao = YoudaoTranslator()
    youdao.translator('测试')
